package qq2564874169.tuaotuao.fx.context;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.Scope;
import qq2564874169.tuaotuao.fx.FxStream;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ContextScope implements Scope {
    private List<Runnable> dispenser = new ArrayList<>();
    private Map<String, Object> beans = new HashMap<>();

    public void destroy() {
        FxStream.create(dispenser).reverse().foreach(Runnable::run);
        dispenser.clear();
        beans.clear();
    }

    @Override
    public Object get(String s, ObjectFactory<?> factory) {
        Object bean = beans.getOrDefault(s, null);
        if (bean == null) {
            bean = factory.getObject();
            beans.put(s, bean);
        }
        return bean;
    }

    @Override
    public Object remove(String s) {
        return beans.remove(s);
    }

    @Override
    public void registerDestructionCallback(String s, Runnable runnable) {
        dispenser.add(runnable);
    }

    @Override
    public Object resolveContextualObject(String s) {
        return null;
    }

    @Override
    public String getConversationId() {
        return null;
    }
}
